package cdu.sl.aichatdemo.mapper;

import cdu.sl.aichatdemo.pojo.entity.CustomChatMemory;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>
 * 自定义聊天记忆 Mapper 接口
 * </p>
 *
 * @author Sunlin
 * @since 2025-08-28
 */
public interface CustomChatMemoryMapper extends BaseMapper<CustomChatMemory> {

    /**
     * 根据对话ID查询对话记录
     */
    @Select("SELECT * FROM custom_chat_memory WHERE conversation_id = #{conversationId}  ORDER BY order_index ASC")
    List<CustomChatMemory> selectByConversationId(@Param("conversationId") String conversationId);

    /**
     * 根据用户ID查询历史对话记录（每个对话ID只返回第一条记录作为摘要）
     */
    @Select("SELECT DISTINCT conversation_id, user_id, title, MIN(created_at) as created_at " +
            "FROM custom_chat_memory " +
            "WHERE user_id = #{userId} " +
            "GROUP BY conversation_id,user_id,title " +
            "ORDER BY created_at DESC")
    List<CustomChatMemory> selectHistoryByUserId(@Param("userId") Long userId);

    /**
     * 根据用户ID和对话ID查询具体对话内容
     */
    @Select("SELECT * FROM custom_chat_memory " +
            "WHERE user_id = #{userId} AND conversation_id = #{conversationId}  " +
            "ORDER BY order_index ASC")
    List<CustomChatMemory> selectByUserIdAndConversationId(@Param("userId") Long userId,
                                                          @Param("conversationId") String conversationId);
}
